import log from "./utils.log";
import config from "../config/server.config";
import toast from "../utils/utils.toast";
import {
	login
} from '@/api/my.js'

//请求头
const getHeader = () => {
	return {
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': uni.getStorageSync("token"), //toke
	}
}
/**
 * @param method 请求方式
 * @param url 请求URL
 * @param data 请求数据
 * @returns {Promise}
 */
const service = function(method, url, data) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.SERVER_URL + url,
			data: data,
			header: getHeader(),
			method: method,
			success: (res) => {
				console.log(res, '========');
				switch (res.data.code) {
					case 200: {
						let json = res.data;
						log.capsule('请求成功:', url, 'success')
						resolve(json);
						break;
					}
					case 500: {
						toast.error(res.data.msg)
						resolve(res);
						break;
					}
					//token过期 帮用户重新登录
					case 501: {
						// 获取登录凭证
						uni.login({
							provider: 'weixin',
							success: res1 => {
								console.log(res1);
								login({
									code: res1.code
								}).then(res2 => {
									console.log(res2);
									uni.setStorageSync(
										"token",
										res2.token);
									toast.info('重新获取数据中....')
									console.log('重新登录1111111111111111111');
									// 登录成功后 重新跳转页面
									let pages = getCurrentPages();
									let prevpage = pages[pages.length - 1]
									console.log(prevpage.route);
									uni.reLaunch({
										url: '/' +
											prevpage
											.route
									});
								})
							},
						});
						reject();
						break;
					}
				}
			},
			fail: (res) => {
				log.capsule('请求失败:', url, 'danger')
				log.danger(JSON.stringify(res.data))
				toast.error('网络错误')
				reject(res);
			},
			complete: (res) => {
				// log.capsule('请求完成:',url,'primary')
			}
		});
	})
}
export default service